package com.farecrawler.app.utils;

import java.util.Calendar;
import java.util.Date;

public class DateUtils {
	
	
	public static Date add(Date date, int field, int amount){
		
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(field, amount);
		
		return cal.getTime();
	}
	
	/**
	 * Return short name for month
	 * 
	 * @param month - Use with reference to Calendar.MONTH
	 * @return
	 */
	public static String getShortMonth(int month) {
		String[] monthArr = new String[]{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
		return monthArr[month];
	}
	
	/**
	 * Return year as the last 2 digits. e.g. 2010 returned as 10
	 * 
	 * @param year
	 * @return
	 */
	public static String getShortYear(int year) {
		String yearString = String.valueOf(year);
		
		String result = null;
		if(yearString.length() == 4) {
			result = yearString.substring(2);
		}
		return result;
	}
	
	/**
	 * Concat year and month as a String. e.g. 12, 2010 will returned as 201012
	 * 
	 * @param month
	 * @param year
	 * @return
	 */
	public static String convertAsYearMonth(Integer month, Integer year) {
		
		if(isMonthValid(month)){

			String monthString = appendZeroToSingleDigit(month);			
			String yearString = String.valueOf(year); 
			return yearString + monthString;
			
		}else {
			throw new RuntimeException("Month value, "+month+" is invalid. Please " +
					"input a value from 1-12");
		}
	}
	
	/**
	 * Convert an Integer Day to a String
	 * 
	 * @param day
	 * @return
	 */
	public static String convertAsDay(Integer day) {
		
		if(isDayValid(day)) {
			
			String dayString = appendZeroToSingleDigit(day);
			return dayString;
			
		}else {
			throw new RuntimeException("Day value, "+day+" is invalid. Please " +
			"input a value from 1-31");
		}
	}
	
	/**
	 * Check if month is valid. Value must be from 1-12.
	 * 
	 * @param month
	 * @return
	 */
	public static boolean isMonthValid(Integer month) {
		
		boolean isMonthValid = false;
		
		if((month > 0) && (month < 13))
			isMonthValid = true;
		
		return isMonthValid;
	}
	
	/**
	 * Check if day is valid. Value must be from 1-31.
	 * 
	 * @param day
	 * @return
	 */
	protected static boolean isDayValid(Integer day) {
		
		boolean isDayValid = false;
		
		if((day > 0) && (day < 32))
			isDayValid = true;
		
		return isDayValid;
	}
	
	/**
	 * Append a 0 to a single digit. e.g. A value "2" will be returned as "02"
	 * 
	 * @param digit
	 * @return
	 */
	protected static String appendZeroToSingleDigit(Integer digit) {
		
		String digitString = "";
		
		if(digit < 10) {
			digitString = "0" + (String.valueOf(digit));
		}else {
			digitString = String.valueOf(digit);
		}
		return digitString;
	}

}
